<!DOCTYPE html>
<html>
<head>
	<title>生成二叉树</title>
</head>
<body>
<script type="text/javascript">
const targetArr = [8,3,10,1,6,14,4,7,13];//要遍历的数组
</script>
<script type="text/javascript">
function BinaryTree1(nodeArr){//封装一个二叉树的函数
    var Node = function(key){//设置一个节点函数，根节点的key是值，left表示左箭头，right表示右箭头
        this.key = key;
        this.left = null;
        this.right = null;
    };
    this.root = new Node(nodeArr[0]);;//准备一个根节点的坑。
    var insert = function(root, data, type) {
        let newDode = new Node(data);

        if(type == 'l') {
            root.left = newDode;
        }else if(type == 'r') {
            root.right = newDode;
        }
        return newDode;
    }
    var result=[], i=1;

    result.push(this.root);// 压入队列
    while(result.length != 0){
        let r = result.shift();//压出队列
        if(i < nodeArr.length-1){
            if(nodeArr[i]) {
                result.push(insert(r, nodeArr[i], 'l'));//压入队列            
            }
            if(nodeArr[i+1]) {
                result.push(insert(r, nodeArr[i+1], 'r'));//压入队列
            }
        }

        i += 2;
    }
}

var binaryTree1 = new BinaryTree1(targetArr);//把整个自定义的二叉树函数送给这个变量指针
console.log(binaryTree1);
</script>
</body>
</html>